#ifndef __M_UTIL_H__
#define __M_UTIL_H__

#include "logger.hpp"
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <memory>
#include <string>
#include <mysql/mysql.h>
#include <jsoncpp/json/json.h>

class mysql_util
{
public:
    static MYSQL* mysql_create(const std::string &host, const std::string &username, const std::string &password, 
    const std::string &dbname, uint16_t port = 3306)
    {
        MYSQL* mysql = mysql_init(NULL);
        if(mysql == NULL)
        {
            ELOG("mysql init failed!!");
            return nullptr;
        }
        if(mysql_real_connect(mysql, host.c_str(), username.c_str(), password.c_str(), dbname.c_str(), port, NULL, 0) == NULL)
        {
            ELOG("connect mysql server failed: %s", mysql_error(mysql));
            mysql_close(mysql);//防止内存泄露
            return nullptr;
        }
        if(mysql_set_character_set(mysql, "utf8") != 0)
        {
            ELOG("set client character failed: %s", mysql_error(mysql));
            mysql_close(mysql);//防止内存泄露
            return nullptr;
        }
        return mysql;
    }
    static bool mysql_exec(MYSQL* mysql, const std::string &sql)
    {
        int ret = mysql_query(mysql, sql.c_str());
        if(ret != 0)
        {
            ELOG("%s sql query failed: %s", sql.c_str(), mysql_error(mysql));
            //这里执行语句失败后就不要释放句柄了，db.hpp中的user_table对象在析构的时候会释放句柄，重复释放则野指针访问
            return false; 
        }
        return true;
    }
    static void mysql_destroy(MYSQL* mysql)
    {
        if(mysql) mysql_close(mysql);
    }
};
class json_util
{
public:
    static bool serialize(const Json::Value& root, std::string& str)
    {
        Json::StreamWriterBuilder swb;
        std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());//用智能指针来管理StreamWriter对象
        std::stringstream ss;
        int ret = sw->write(root, &ss);
        if (ret != 0)
        {
            ELOG("Json::serialize failed!!");
            return false;
        }
        str = ss.str();
        return true;
    }
    static bool deserialize(const std::string& str, Json::Value& root)
    {
        Json::CharReaderBuilder crb;
        std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
        std::string err;
        bool ret = cr->parse(str.c_str(), str.c_str() + str.size(), &root, &err);
        if (ret == false)
        {
            ELOG("json deserialize failed!! %s", err.c_str());
            return false;
        }
        return true;
    }
};
class string_util
{
public:
    static void split(const std::string& src, const std::string& sep, std::vector<std::string>& res)
    {
        //123,345,,,,678
        size_t pos = 0, idx = 0;
        while(idx != std::string::npos)
        {
            idx = src.find(sep, pos);
            if(idx != pos) res.push_back(src.substr(pos, idx - pos)), pos = idx;
            else pos++;
        }
    }
};
class file_util
{
public:
    static bool read(const std::string filename, std::string& body)
    {
        //1.打开文件
        std::ifstream ifs(filename.c_str(), std::ios_base::binary | std::ios_base::in);
        if(ifs.is_open() == false)
        {
            ELOG("%s file open failed!!", filename.c_str());
            return false;
        } 
        //2.获取文件大小
        ifs.seekg(0, std::ios::end);//将文件的读取位置移动到文件末尾处
        size_t filesize = ifs.tellg();//获取文件当前的读取位置
        ifs.seekg(0, std::ios::beg);
        //3.将文件所有数据读取出来
        body.resize(filesize);
        ifs.read(&body[0], filesize);
        //这里不能传递body.c_str()，因为c_str()返回的是const char*，我们的目的就是将内容读取到body里，body的内容必须是可修改的
        if(ifs.good() == false) 
        {
            ELOG("%s file read failed!!", filename.c_str());
            ifs.close();//释放资源，否则内存泄露
            return false;
        }
        //4.关闭文件
        ifs.close();
        return true;
    }
};

#endif